import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;


public class FileWrite {
	private String filename;
	public FileWrite(String filename){
		this.filename = filename;
	}
	
	public void output(){
		String trainingfilename = "e:/trainProdSelection.txt";	
		String testingfilename = "e:/testProdSelection.txt";
		String predictfilename = "e:/"+filename+"_partA.txt";
		File newfile = new File(predictfilename);// new file to store the result
		StringBuffer outputBuffer = new StringBuffer();
		Scanner scanner = null;
		PrintWriter writer = null;
		
		/*
		 * This process will select the best split points and conver the examples
		 */
		SelectSplitPoint selectPoint = new SelectSplitPoint(trainingfilename);
		selectPoint.getPerfectExamples();	
		
		/*
		 * This process will build the decision tree based on the examples which 
		 * has been converted
		 */
		DecisionTree buildTree = new DecisionTree(trainingfilename);
		Node root = buildTree.buildDecisionTree();
		
		/*
		 * This part is to add the predicted classification at the end of test data
		 */
		FileRead testfile = new FileRead(testingfilename);
		ArrayList<Data> outputData = testfile.convertExamples(selectPoint);	
		
		try {
			scanner = new Scanner(new File(testingfilename));
			int line = 0;
			while(scanner.hasNextLine()){
				//System.out.println("test");
				outputBuffer.append(scanner.nextLine()+" ");
				outputBuffer.append(buildTree.search(outputData.get(line),root));
				outputBuffer.append("\r\n");
				line++;
			}
		} catch (FileNotFoundException e) {
			System.err.println("Cannot find the file");
		} finally {
			if (scanner != null)
				scanner.close();
		}
		
		try {
			writer = new PrintWriter(new FileWriter(newfile),true);
			writer.println(outputBuffer.toString());
		} catch (IOException e) {
			System.err.println("Writing error");
		} finally {
			if (writer != null)
				writer.close();
		}	
			
	}
}
